package tr.edu.yildiz.ce.dap.appagent.command.prompt;

import java.util.List;
import java.util.StringTokenizer;

import tr.edu.yildiz.ce.dap.appagent.command.deployment.agent.DetailCommand;
import tr.edu.yildiz.ce.dap.appagent.command.deployment.base.AbstractAgentCommand;
import tr.edu.yildiz.ce.dap.appagent.command.deployment.base.CommandConstants;
import tr.edu.yildiz.ce.dap.appagent.exception.BasicAgentException;
import tr.edu.yildiz.ce.dap.appagent.model.App;
import tr.edu.yildiz.ce.dap.appagent.model.Component;
import tr.edu.yildiz.ce.dap.appagent.model.DapMessage;
import tr.edu.yildiz.ce.dap.appagent.process.base.AbstractProcess;

public class DetailPromptCommand extends BasicPromptCommand{

	public DetailPromptCommand(AbstractProcess process) {
		super(process);
	}

	@Override
	protected AbstractAgentCommand prepareAgentCommand(AbstractProcess process,String commandStr) throws BasicAgentException  {
		StringTokenizer sTokenizer = new StringTokenizer(commandStr," ");
		String command = sTokenizer.nextToken();
		String name = null;
		String version = null;
		while (sTokenizer.hasMoreElements()) {
			String pType = (String) sTokenizer.nextElement();
			if (pType.equals(CommandConstants.PARAMETER_TYPE.NAME)){
				name = sTokenizer.nextToken();
			}else if (pType.equals(CommandConstants.PARAMETER_TYPE.VERSION)){
				version = sTokenizer.nextToken(); 
			}
		}
		if (name == null || version == null)
			throw new BasicAgentException("List command can't be used without name and version parameters : app-agent -n app_name -v app_version");
		
		return new DetailCommand(process, name, version);
	}

	@Override
	protected void processResponse(DapMessage response) {
		List<Component> componentList = response.getComponentList().getComponent();
		System.out.println("Components of " + response.getAppName() + "(" + response.getAppVersion() + ")");
		StringBuilder sBuilder = new StringBuilder();
		for (Component c : componentList) {
			sBuilder.append(c.getName() + " " + c.getVersion() + " " + c.getVersion()  );
			List<String> actionList = c.getActions().getAction();
			sBuilder.append("[");
			int i = 0;
			for (String string : actionList) {
				if (i > 0 )
					sBuilder.append(",");
				sBuilder.append(string);
				i++;
			}
			sBuilder.append("]");
			System.out.println(sBuilder.toString());
		}
	}

}
